<template>
  <div class="login">
    <h1>登录</h1>
    <form @submit.prevent="login">
      <input v-model="username" type="text" placeholder="用户名" required />
      <input v-model="password" type="password" placeholder="密码" required />
      <button type="submit">登录</button>
      <p class="register-link">没有账号？<router-link to="/register">注册</router-link></p>
      <!-- 或者使用： -->
      <!-- <p class="register-link">没有账号？<a href="#" @click.prevent="goToRegister">注册</a></p> -->
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Login',
  data() {
    return {
      username: '',
      password: ''
    };
  },
  methods: {
    login() {
      axios.post('http://localhost:3000/login', {
        username: this.username,
        password: this.password
      })
      .then(response => {
        const token = response.data.token;
        localStorage.setItem('token', token);
        this.$router.push('/home'); 
      })
      .catch(error => {
        alert('登录失败，请检查用户名和密码');
        console.error('登录失败', error);
      });
    },
    goToRegister() {
      this.$router.push('/register').catch(err => {
        // 捕获重复导航错误
        if (err.name !== 'NavigationDuplicated') {
          console.error('导航错误:', err);
        }
      });
    }
  }
};
</script>
 

<style scoped>
.login {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

h1 {
  color: #6B5B4B; /* 深米色标题 */
  margin-bottom: 2rem;
  font-size: 2.5em;
  text-shadow: 1px 1px 2px rgba(255, 255, 255, 0.5);
}

form {
  background-color: white;
  padding: 2rem;
  border-radius: 15px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

input {
  width: 100%;
  padding: 12px 20px;
  margin: 10px 0;
  border: 2px solid #E0D7C9; /* 浅米色边框 */
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

input:focus {
  outline: none;
  border-color: #C2B8A6; /* 深米色焦点边框 */
  box-shadow: 0 0 5px rgba(194, 184, 166, 0.3);
}

button {
  width: 100%;
  padding: 12px;
  margin-top: 15px;
  background-color: #D3C0B1; /* 米色按钮 */
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1.1rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #B8A08B; /* 深米色悬停效果 */
}

.register-link {
  color: #6B5B4B; /* 深米色文字 */
  margin-top: 1.5rem;
  text-align: center;
}

.register-link a {
  color: #A8927C; /* 中等米色链接 */
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.register-link a:hover {
  color: #8C7A67; /* 深米色悬停 */
  text-decoration: underline;
}

@media (max-width: 480px) {
  form {
    padding: 1.5rem;
  }
  
  h1 {
    font-size: 2rem;
  }
}
</style>